package org.shop.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

public class FileUtil {

	/**
	 * 将MultipartFile 转化为File
	 * 
	 * @param mf
	 * @return
	 */
	public static File multipartFileToFile(MultipartFile mf, String path) {
		File uploadFile = null;
		try {
			if(mf!=null){
				String realFileName = mf.getOriginalFilename();
				CommonsMultipartFile cf = (CommonsMultipartFile) mf;
				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdir();
				}
				uploadFile = new File(path + realFileName);
				cf.getFileItem().write(uploadFile);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return uploadFile;
	}

	/**
	 * 读取excel中的内容
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String readExcelToString(File file) throws IOException {
		StringBuffer sr = new StringBuffer();
		List<List<String>> datas = ReadExcel.readExcel(file);
		Integer hangLength = datas.size();
		for (int i = 0; i < hangLength; i++) {
			List<String> lie = datas.get(i);
			for (int j = 0; j < lie.size(); j++) {
				sr.append(lie.get(j));
			}
		}
		return sr.toString();
	}

	/**
	 * 读取txt
	 * @param file
	 * @return
	 */
	public static String readTxtToString(File file) {
		StringBuffer sr=new StringBuffer();
		try {
			String encoding = "UTF-8";
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				sr.append(lineTxt);
			}
			read.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sr.toString();
	}
	
	public static void copyFileToOtherPath(File file,String path){
		try {
			FileInputStream fin=new FileInputStream(file);
			FileOutputStream fou=new FileOutputStream(path);
			byte[]data=new byte[2048];
			int r ;
			while((r=fin.read(data))>0){
				fou.write(data);
			}
			fin.close();
			fou.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
